package com.grj.service.common.listener;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.grj.api.user.ArticleApi;
import com.grj.model.article.entity.Liked;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 14505
 */
@Component
public class RabbitMQListener {

    @Resource
    private ArticleApi articleApi;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @RabbitListener(queues = "queue")
    public void listenerA(Message message, Channel channel, String msg)throws Exception{
        Set<String> keys = stringRedisTemplate.keys("article::like::*");
        if(keys.size() == 0){ return; }
        ArrayList<Liked> list = new ArrayList<>();
        keys.forEach(k->{
            BoundHashOperations<String, String, String> ops = stringRedisTemplate.boundHashOps(k);
            Map<String, String> entries = ops.entries();
            if(entries.size() == 0){
                return;
            }
            Set<String> keySet = entries.keySet();
            List<Liked> collect = keySet.stream().map(j -> {
                Liked liked = new Liked();
                liked.setAid(k.replaceAll("article::like::", ""));
                liked.setUid(j);
                liked.setStatus(Integer.parseInt(entries.get(j)));
                return liked;
            }).collect(Collectors.toList());
            list.addAll(collect);
        });

        Map<String, Object> map = new HashMap<>();
        list.forEach(i->{
            map.put("uid",i.getUid());
            map.put("aid",i.getAid());
        });

        String k = JSONUtil.toJsonStr(new ArrayList<>(keys));
        String s = JSONUtil.toJsonStr(list);
        articleApi.likes(k+"///"+s);

        System.out.println(msg);
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    }



}
